package com.wiken.servicecommon.common;

import com.wiken.servicecommon.common.exception.DefaultException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class TokenUtil {
    private static final String SECRET = "wiken_family_safe_everyday";
    private static final long EXPIRE = 7200L; // 2小时

    public static String createToken(Map<String, Object> claims) {
        Date expiration = new Date(System.currentTimeMillis() + EXPIRE * 1000);
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            return null;
        }
    }

    public static String getUserIdByToken(String token){
        if(token == null) throw new DefaultException(Code.ERROR_AUTHORIZATION, "请重新登陆");

        Claims claims = parseToken(token);

        if(claims == null) throw new DefaultException(Code.ERROR_AUTHORIZATION, "请重新登陆");

        String userId = claims.get("userId", String.class);

        if(userId == null) throw new DefaultException(Code.ERROR_AUTHORIZATION, "请重新登陆");

        return userId;
    }

    public static boolean hasSameUser(String token, String userId){
        String parseUserId = getUserIdByToken(token);

        if(parseUserId.equals(userId)) return true;

        return false;
    }
}
